package ssh

import (
	"gitee.com/YunFeiGuoJi/kubetools/pkg/connector"
	"sync"
	"time"

	kubekeyapiv1alpha1 "gitee.com/YunFeiGuoJi/kubetools/apis/kubetools/v1alpha1"
)

type Dialer struct {
	lock        sync.Mutex
	connections map[int]connector.Connection
}

func NewDialer() *Dialer {
	return &Dialer{
		connections: make(map[int]connector.Connection),
	}
}

func (dialer *Dialer) Connect(host kubekeyapiv1alpha1.HostCfg) (connector.Connection, error) {
	var err error

	dialer.lock.Lock()
	defer dialer.lock.Unlock()

	conn, _ := dialer.connections[host.Index]

	opts := Cfg{
		Username:   host.User,
		Port:       host.Port,
		Address:    host.Address,
		Password:   host.Password,
		PrivateKey: host.PrivateKey,
		KeyFile:    host.PrivateKeyPath,
		Timeout:    30 * time.Second,
	}
	conn, err = NewConnection(opts)
	if err != nil {
		return nil, err
	}
	dialer.connections[host.Index] = conn

	return conn, nil
}
